package java;

import java.util.*;

public class Question36 {
    public static void main(String[] args) {
        char[][] chars = {
                            {'5','3','.','.','7','.','.','.','.'},
                            {'6','.','.','1','9','5','.','.','.'},
                            {'.','9','8','.','.','.','.','6','.'},
                            {'8','.','.','.','6','.','.','.','3'},
                            {'4','.','.','8','.','3','.','.','1'},
                            {'7','.','.','.','2','.','.','.','6'},
                            {'.','6','.','.','.','.','2','8','.'},
                            {'.','.','.','4','1','9','.','.','5'},
                            {'.','.','.','.','8','.','.','7','9'}
                        };

        System.out.println(isValidSudoku(chars));
    }
    public static boolean isValidSudoku(char[][] board) {
        if (board == null || board.length != 9){
            return false;
        }
        Map<Integer,Set<Character>> boxMap = new HashMap<>();
        Map<Integer,Set<Character>> rowMap = new HashMap<>();
        Map<Integer,Set<Character>> columnMap = new HashMap<>();
        for (int i = 0; i < 9; i ++){
            for (int j = 0; j < 9; j ++){
                if (board[i][j] == '.'){
                    continue;
                }
                int boxNum = (i / 3) * 3 + j / 3;
                boolean check1 = isValid(boxNum,boxMap,board[i][j]);
                boolean check2 = isValid(i,rowMap,board[i][j]);
                boolean check3 = isValid(j,columnMap,board[i][j]);
                if (!check1 || !check2 || !check3){
                    return false;
                }
            }
        }
        return true;
    }

    private static boolean isValid(int num, Map<Integer, Set<Character>> map, char c) {

        if (!map.containsKey(num)){
            map.put(num,new HashSet<>());
            map.get(num).add(c);
        }else {
            Set<Character> temp = map.get(num);
            if (!temp.contains(c)){
                temp.add(c);
            }else {
                return false;
            }
        }
        return true;
    }
}
